package com.bigfish.gbs.controller;

import com.alibaba.fastjson.JSON;
import com.bigfish.gbs.dao.SupplierMapper;
import com.bigfish.gbs.dto.Result;
import com.bigfish.gbs.dto.SupplierVO;
import com.bigfish.gbs.entity.Supplier;
import com.bigfish.gbs.entity.User;
import com.bigfish.gbs.enums.ResultEnum;
import com.bigfish.gbs.service.AccountService;
import com.bigfish.gbs.service.SupplierService;
import com.bigfish.gbs.service.UserService;
import com.bigfish.gbs.util.CommonUtil;
import com.bigfish.gbs.util.MD5Util;
import com.bigfish.gbs.util.ResultUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * 用户管理相关的接口
 * @Author Joycessh
 * @Description
 * @Date 12/12/18 4:16 PM
 */
@Api(value = "用户管理", description = "用户账号的增删改查接口")
@RestController
@RequestMapping("/user")
public class UserController extends BasicAction {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取角色关联的(roleId)对应用户列表
     * @author Joycessh
     * @param roleId
	 * @param currentPage
	 * @param pageSize
	 * @param name
     * @return com.bigfish.gbs.dto.Result
     * @date 12/13/18 3:44 PM
     */
    @ApiOperation(value = "获取角色关联的(roleId)对应用户列表", httpMethod = "GET")
    @GetMapping("/list")
    public Result getUserListByRoleId(@RequestParam Integer currentPage,     //
                                      @RequestParam Integer pageSize,
                                      @RequestParam(value = "roleId", required = true) Integer roleId,
                                      @RequestParam(value = "name", required = false, defaultValue = "")
                                                  String name ) { //value用来指定要传入值的id名称，required用来指示参数是否必须绑定,defaultValue指定默认值

        PageHelper.startPage(currentPage, pageSize);
        List<User> users = userService.getUserListByRoleIdAndName(roleId, name);
        users.forEach(user->user.setPassword(null));
        PageInfo pageInfo = new PageInfo(users);
        return ResultUtil.retFormat(ResultEnum.SUCCESS).addData("users", pageInfo);

    }

    @ApiOperation(value = "添加会员", httpMethod = "POST")
    @PostMapping("/member")
    public Result addMember(@RequestBody HashMap map) {
        User user = JSON.parseObject(JSON.toJSONString(map.get("params")), User.class);
        String userId = user.getUserId();
        System.out.println("userId:" + user.getUserId());
        if (accountService.isAccountExistByUid(userId)) {
            // 账户已存在
            return ResultUtil.retParams(1111, "账户已存在");
        }
        String salt = CommonUtil.getRandomString(6);
        user.setPassword(MD5Util.md5("123456" + salt));
        user.setSalt(salt);
        if (accountService.registerAccount(user)) {
            //LogExeManager.getInstance().executeLogTask(LogTaskFactory.registerLog(uid, IpUtil.getIpFromRequest(WebUtils.toHttp(request)), (short) 1, "注册成功"));
            return ResultUtil.retFormat(ResultEnum.SUCCESS);

        } else {
            //LogExeManager.getInstance().executeLogTask(LogTaskFactory.registerLog(uid, IpUtil.getIpFromRequest(WebUtils.toHttp(request)), (short) 0, "注册失败"));
            return ResultUtil.retFormat(ResultEnum.FAIL);
        }
    }

    @ApiOperation(value = "删除会员", httpMethod = "DELETE")
    @DeleteMapping("/member/{userId}")
    public Result deleteMember(@PathVariable String userId) {
        userService.deleteAuthorityUserRole(userId, 103);
        boolean flag = userService.deleteUserByUserId(userId);
        if (flag) {
            return ResultUtil.retFormat(ResultEnum.SUCCESS);
        }else {
            return ResultUtil.retFormat(ResultEnum.FAIL);
        }
    }

    /**
     * 修改用户账号信息
     * @author Joycessh
     * @param map
     * @return com.bigfish.gbs.dto.Result
     * @date 12/17/18 8:17 PM
     */
    @ApiOperation(value = "更新用户账号信息", httpMethod = "PUT")
    @PutMapping("/update")
    public Result updateUser(@RequestBody HashMap map) {
        User user = JSON.parseObject(JSON.toJSONString(map.get("params")), User.class);
        boolean flag = userService.updateMember(user);
        if (flag) {
            return ResultUtil.retFormat(ResultEnum.SUCCESS);
        }else {
            return ResultUtil.retFormat(ResultEnum.FAIL);
        }
    }

    @ApiOperation(value = "添加商家", httpMethod = "POST")
    @PostMapping("/supplier")
    public Result addSupplier(@RequestBody HashMap map) {
        SupplierVO supplierVO = JSON.parseObject(JSON.toJSONString(map.get("params")), SupplierVO.class);
        User user = supplierVO.getUser();
        String userId = user.getUserId();
        System.out.println("userId:" + user.getUserId());
        if (accountService.isAccountExistByUid(userId)) {
            // 账户已存在
            return ResultUtil.retParams(1111, "账户已存在");
        }
        String salt = CommonUtil.getRandomString(6);
        user.setPassword(MD5Util.md5("123456" + salt));
        user.setSalt(salt);

        Supplier supplier = supplierVO.getSupplier();
        supplierService.addSupplierMsg(supplier);

        if (accountService.registerSupplier(user)) {
            //LogExeManager.getInstance().executeLogTask(LogTaskFactory.registerLog(uid, IpUtil.getIpFromRequest(WebUtils.toHttp(request)), (short) 1, "注册成功"));
            return ResultUtil.retFormat(ResultEnum.SUCCESS);

        } else {
            //LogExeManager.getInstance().executeLogTask(LogTaskFactory.registerLog(uid, IpUtil.getIpFromRequest(WebUtils.toHttp(request)), (short) 0, "注册失败"));
            return ResultUtil.retFormat(ResultEnum.FAIL);
        }
    }

    @ApiOperation(value = "删除商家", httpMethod = "DELETE")
    @DeleteMapping("/supplier/{userId}")
    public Result deleteSupplier(@PathVariable String userId) {
        userService.deleteAuthorityUserRole(userId, 104);
        boolean flag = userService.deleteUserByUserId(userId);
        if (flag) {
            return ResultUtil.retFormat(ResultEnum.SUCCESS);
        }else {
            return ResultUtil.retFormat(ResultEnum.FAIL);
        }
    }

    @ApiOperation(value = "添加管理员", httpMethod = "POST")
    @PostMapping("/admin")
    public Result addAdmin(@RequestBody HashMap map) {
        User user = JSON.parseObject(JSON.toJSONString(map.get("params")), User.class);
        String userId = user.getUserId();
        System.out.println("userId:" + user.getUserId());
        if (accountService.isAccountExistByUid(userId)) {
            // 账户已存在
            return ResultUtil.retParams(1111, "账户已存在");
        }
        String salt = CommonUtil.getRandomString(6);
        user.setPassword(MD5Util.md5("123456" + salt));
        user.setSalt(salt);
        if (accountService.registerAdmin(user)) {
            //LogExeManager.getInstance().executeLogTask(LogTaskFactory.registerLog(uid, IpUtil.getIpFromRequest(WebUtils.toHttp(request)), (short) 1, "注册成功"));
            return ResultUtil.retFormat(ResultEnum.SUCCESS);

        } else {
            //LogExeManager.getInstance().executeLogTask(LogTaskFactory.registerLog(uid, IpUtil.getIpFromRequest(WebUtils.toHttp(request)), (short) 0, "注册失败"));
            return ResultUtil.retFormat(ResultEnum.FAIL);
        }
    }

    @ApiOperation(value = "删除管理员", httpMethod = "DELETE")
    @DeleteMapping("/admin/{userId}")
    public Result deleteAdmin(@PathVariable String userId) {
        userService.deleteAuthorityUserRole(userId, 102);
        supplierService.delSupplierMsg(userId);
        boolean flag = userService.deleteUserByUserId(userId);
        if (flag) {
            return ResultUtil.retFormat(ResultEnum.SUCCESS);
        }else {
            return ResultUtil.retFormat(ResultEnum.FAIL);
        }
    }

    @ApiOperation(value = "获取供应商信息", httpMethod = "Get")
    @GetMapping("/supplier/{userId}")
    public Result getSupplierMsg(@PathVariable String userId) {

        List<Supplier> list = new LinkedList<>();
        Supplier supplier = supplierService.getMsgByUserId(userId);
        list.add(supplier);
        return ResultUtil.retFormat(ResultEnum.SUCCESS).addData("msg", list);
    }

}
